#include "StdAfx.h"
#include "ShareMemory.h"
 
long CShareMemory::m_Ref=0;
HANDLE CShareMemory::m_MemHandle=NULL;
PVOID  CShareMemory::m_MemShare=NULL;
CMyMutex CShareMemory::m_Mutex;

#define  BUF_SIZE 10240

PVOID CShareMemory::GetShareMemory()
{
	m_Mutex.Enter();
	if (m_MemHandle==NULL && m_MemShare==NULL)
	{
		m_MemHandle=CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE|SEC_COMMIT,0,BUF_SIZE,"Global\\APIHookShare");
	}
	if (m_MemHandle!=NULL)
	{
		m_MemShare=MapViewOfFile(m_MemHandle,FILE_MAP_ALL_ACCESS,0,0,0);
		if (m_MemShare!=NULL)
		{
			SecureZeroMemory(m_MemShare,BUF_SIZE);
		}
	}
	InterlockedIncrement(&m_Ref);

	m_Mutex.Leave();
	return m_MemShare;
}
 

void CShareMemory::ReleaseMemory()
{
	m_Mutex.Enter();
	if (m_Ref>0)
	{
		InterlockedDecrement(&m_Ref);
	}
	
	if (m_Ref==0 && m_MemShare!=NULL)
	{
		UnmapViewOfFile(m_MemShare);
		m_MemShare=NULL;
		if (m_MemHandle!=NULL)
		{
			CloseHandle(m_MemHandle);
		}
	}
	m_Mutex.Leave();
}